<?php
namespace app\controllers\api\account;

/**
 * reg
 */
use fate\http\Request;
use app\models\User;
use app\libs\Validator;
use app\services\MailService;
use app\libs\Util;
use app\libs\Sys;

class RegisterController extends \fate\web\PureController {
    public function run() {
        global $_G;

        // 开放注册
        if(!Sys::canRegister()) {
            $this->ajaxReturn(null, 500001);
            exit;
        }

        $req = Request::getInstance();

        $nick = Util::plainText($req->getParameter('nick'));
        $password = $req->getParameter('password');
        $email = Util::plainText($req->getParameter('email'));
        $verifyCode = Util::plainText($req->getParameter('verify_code'));

        // 邮箱合法性
        if(!Validator::permittedEmail($email)) {
            $this->ajaxReturn(null, 100003);
            exit;
        }

        // 昵称 邮箱是否已经存在
        $user = new User();
        $has = $user->count("user_name='{$nick}'") > 0;
        if($has) {
            $this->ajaxReturn(null, 100005);
            exit;
        }
        $has = $user->count("email='{$email}'") > 0;
        if($has) {
            $this->ajaxReturn(null, 100006);
            exit;
        }

        if( !$nick || !Validator::validateNickname($nick) ) {
            $this->ajaxReturn(null, 100001);
            exit;
        }
        if(!$password) {
            $this->ajaxReturn(null, 100002);
            exit;
        }
        if( !$email || !Validator::validateEmail($email) ) {
            $this->ajaxReturn(null, 100003);
            exit;
        }
        if( !(new MailService())->validateRegisterCode($email, $verifyCode) ) {
            $this->ajaxReturn(null, 100004);
            exit;
        }

        $ret = [
            'user_name' => $nick,
            'password' => md5($password),
            'email' => $email,
            'birthday' => $_G['now_time'],
            'reg_time' => $_G['now_time'],
            'status' => 1
        ];

        $rs = $user->insert($ret);

        $this->ajaxReturn(null);
    }
}
